import { defineStore } from 'pinia'

// 从localStorage获取已保存的标签数据
const getStoredTags = () => {
  try {
    const visitedViews = JSON.parse(localStorage.getItem('visitedViews')) || []
    const cachedViews = JSON.parse(localStorage.getItem('cachedViews')) || []
    return { visitedViews, cachedViews }
  } catch (error) {
    console.error('读取保存的标签数据失败:', error)
    return { visitedViews: [], cachedViews: [] }
  }
}

// 保存标签数据到localStorage
const saveTags = (visitedViews, cachedViews) => {
  try {
    localStorage.setItem('visitedViews', JSON.stringify(visitedViews))
    localStorage.setItem('cachedViews', JSON.stringify(cachedViews))
  } catch (error) {
    console.error('保存标签数据失败:', error)
  }
}

// 获取初始状态
const { visitedViews, cachedViews } = getStoredTags()

export const useTagsStore = defineStore('tags', {
  state: () => ({
    visitedViews: visitedViews,
    cachedViews: cachedViews,
  }),

  actions: {
    /**
     * 添加一个新视图到标签页和缓存
     * @param {Object} view - 路由视图对象
     */
    addView(view) {
      this.addVisitedView(view)
      this.addCachedView(view)
      // 保存到localStorage
      saveTags(this.visitedViews, this.cachedViews)
    },

    /**
     * 添加一个新视图到已访问标签
     * @param {Object} view - 路由视图对象
     */
    addVisitedView(view) {
      if (this.visitedViews.some((v) => v.path === view.path)) return
      this.visitedViews.push({
        name: view.name,
        path: view.path,
        title: view.meta?.title || 'unknown',
        affix: view.meta?.affix || false,
      })
      // 保存到localStorage
      saveTags(this.visitedViews, this.cachedViews)
    },

    /**
     * 添加一个新视图到缓存标签（keepAlive）
     * @param {Object} view - 路由视图对象
     */
    addCachedView(view) {
      if (this.cachedViews.includes(view.name)) return
      if (view.meta?.keepAlive) {
        this.cachedViews.push(view.name)
        // 保存到localStorage
        saveTags(this.visitedViews, this.cachedViews)
      }
    },

    /**
     * 删除指定路径的标签和缓存
     * @param {string} path - 路由路径
     * @returns {Promise<Object>} 删除后的标签和缓存
     */
    delView(path) {
      return new Promise((resolve) => {
        this.delVisitedView(path)
        this.delCachedView(path)
        // 保存到localStorage
        saveTags(this.visitedViews, this.cachedViews)
        resolve({
          visitedViews: [...this.visitedViews],
          cachedViews: [...this.cachedViews],
        })
      })
    },

    /**
     * 删除指定路径的已访问标签
     * @param {string} path - 路由路径
     */
    delVisitedView(path) {
      const index = this.visitedViews.findIndex((v) => v.path === path)
      if (index > -1) {
        this.visitedViews.splice(index, 1)
        // 保存到localStorage
        saveTags(this.visitedViews, this.cachedViews)
      }
    },

    /**
     * 删除指定路径的缓存标签
     * @param {string} path - 路由路径
     */
    delCachedView(path) {
      const view = this.visitedViews.find((v) => v.path === path)
      const index = this.cachedViews.indexOf(view?.name)
      if (index > -1) {
        this.cachedViews.splice(index, 1)
        // 保存到localStorage
        saveTags(this.visitedViews, this.cachedViews)
      }
    },

    /**
     * 删除除指定路径和affix外的所有标签和缓存
     * @param {string} path - 路由路径
     */
    delOthersViews(path) {
      this.visitedViews = this.visitedViews.filter((v) => {
        return v.affix || v.path === path
      })
      const view = this.visitedViews.find((v) => v.path === path)
      if (view?.name) {
        this.cachedViews = [view.name]
      } else {
        this.cachedViews = []
      }
      // 保存到localStorage
      saveTags(this.visitedViews, this.cachedViews)
    },

    /**
     * 删除所有非affix标签和缓存
     */
    delAllViews() {
      this.visitedViews = this.visitedViews.filter((v) => v.affix)
      this.cachedViews = []
      // 保存到localStorage
      saveTags(this.visitedViews, this.cachedViews)
    },

    /**
     * 恢复本地存储中的标签状态
     */
    restoreTags() {
      const { visitedViews, cachedViews } = getStoredTags()
      this.visitedViews = visitedViews
      this.cachedViews = cachedViews
    },

    /**
     * 拖拽切换标签位置
     * @param {number} fromIndex - 原始索引
     * @param {number} toIndex - 目标索引
     */
    moveTag(fromIndex, toIndex) {
      // 确保索引有效
      if (
        fromIndex < 0 ||
        fromIndex >= this.visitedViews.length ||
        toIndex < 0 ||
        toIndex >= this.visitedViews.length ||
        fromIndex === toIndex
      ) {
        return
      }

      // 如果是固定标签，不允许移动
      if (this.visitedViews[fromIndex].affix) {
        return
      }

      // 移动标签
      const tagToMove = this.visitedViews.splice(fromIndex, 1)[0]
      this.visitedViews.splice(toIndex, 0, tagToMove)

      // 保存到localStorage
      saveTags(this.visitedViews, this.cachedViews)
    },

    /**
     * 按照拖拽后的顺序更新缓存视图
     */
    updateCachedViewsOrder() {
      // 创建一个新的缓存视图数组，按照visitedViews的顺序排列
      const newCachedViews = []

      // 遍历访问视图，如果名称在缓存中，则按照当前顺序添加
      this.visitedViews.forEach((view) => {
        if (this.cachedViews.includes(view.name)) {
          newCachedViews.push(view.name)
        }
      })

      // 更新缓存视图
      this.cachedViews = newCachedViews

      // 保存到localStorage
      saveTags(this.visitedViews, this.cachedViews)
    },

    /**
     * 清空tags 清空缓存
     */
    clearTags() {
      this.visitedViews = []
      this.cachedViews = []
      // 清空localStorage
      localStorage.removeItem('visitedViews')
      localStorage.removeItem('cachedViews')
    },
  },
})
